/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.session.distributed.common;

import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.lock.service.api.api.DistributedLock;
import io.iec.edp.caf.lock.service.api.api.DistributedLockFactory;
import io.iec.edp.caf.lockservice.api.IDistributedLock;
import io.iec.edp.caf.lockservice.api.IDistributedLockFactory;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import lombok.SneakyThrows;

public class DistributedLockWrapper implements Lock {

  private final String lockId;

  public DistributedLockWrapper(String funcInstId) {
    this.lockId = funcInstId;
  }

  @Override
  public void lock() {
    buildLock(-1, TimeUnit.SECONDS);
    if (!innerLock.isAcquired()) {
      throw new RuntimeException();
    }
  }

  @Override
  public void lockInterruptibly() throws InterruptedException {
    lock();
  }

  @Override
  public boolean tryLock() {
    throw new RuntimeException("未实现");
  }

  @Override
  public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
    buildLock(time, unit);
    return innerLock.isAcquired();
  }

  @SneakyThrows
  @Override
  public void unlock() {
    if (innerLock != null) {
      innerLock.close();
    }
  }

  @Override
  public Condition newCondition() {
    return null;
  }

  private static final Duration lockTimeOut = Duration.ofSeconds(8);
  private DistributedLock innerLock;

  private void buildLock(long time, TimeUnit unit) {
//    if (innerLock != null) {
//      throw new RuntimeException("重复加锁");
//    }
    //TODO: IDistributedLockFactory不支持设置等待时间, 需要提供
    //TODO: IDistributedLock只提供unlock(close)未提供lock接口, 需要提供
    innerLock = SpringBeanUtils
        .getBean(DistributedLockFactory.class).createLock(lockId, lockTimeOut);
  }
}
